package com.shop.item.api.service.impl;

import com.shop.common.entity.item.*;
import com.shop.common.model.InputBean;
import com.shop.common.model.ServiceBean;
import com.shop.common.model.param.item.*;
import com.shop.common.model.param.user.UserPayInput;
import com.shop.common.model.param.user.UserPayLogInput;
import com.shop.common.model.result.item.ItemBaseOutput;
import com.shop.common.model.result.item.ItemDetailsOutput;
import com.shop.common.model.result.item.ItemExtOutput;
import com.shop.common.model.result.item.LabelOutput;
import com.shop.common.model.result.user.UserPayOutput;
import com.shop.common.tmpl.BaseService;
import com.shop.common.util.DateUtil;
import com.shop.common.util.state.DataStatus;
import com.shop.common.util.state.ItemStatus;
import com.shop.item.atom.atomsvc.IItemAtomService;
import com.shop.item.atom.atomsvc.IItemEditAtomService;
import com.shop.item.atom.atomsvc.IItemExtAtomService;
import com.shop.item.api.model.Item;
import com.shop.item.api.service.IItemService;
import com.shop.item.atom.atomsvc.ILabelAtomService;
import com.shop.item.feign.user.IUserAtomFeignClientSvc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ItemServiceImpl extends BaseService implements IItemService {
    final static Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);

    @Autowired
    IItemAtomService itemApiService;
    @Autowired
    IItemEditAtomService itemEditApiService;
    @Autowired
    IItemExtAtomService itemExtApiService;
    @Autowired
    ILabelAtomService labelAtomService;
    @Autowired
    IUserAtomFeignClientSvc iUserAtomFeignClientSvc;

    @Override
    public ServiceBean<Integer> addItemBase(InputBean<ItemBaseInput> inputBean) {
        ItemBaseInput itemBase = inputBean.getParam();
        UserPayOutput userPayOutput = iUserAtomFeignClientSvc.qryUserPayByUserId(itemBase.getUserId());
        if (itemBase.getSellingPrice().intValue() > userPayOutput.getIntegral()) {
            return resultFailed("用户积分不足");
        }


        Date now = DateUtil.newNowDate();
        itemBase.setCreateTime(now);
        itemBase.setStatus(ItemStatus.STATUS_WAIT.value());
        itemBase.setDataStatus(DataStatus.USE.value());
        itemBase.setDiscountPrice(itemBase.getSellingPrice());
        ServiceBean<Integer> serviceBean = itemApiService.addItemBase(itemBase);
        Integer itemId = serviceBean.getData();
        if (!serviceBean.isSuccess()) {
            return serviceBean;
        }

        //初始化商品标签信息 start
        List<ItemLabelInput> labelInputList = new ArrayList<>();
        List<String> labelNames = new ArrayList<>();
        if (itemBase.getItemNew() == 1) {
            labelNames.add("全新");
        }
        char[] transportTypes = itemBase.getTransportType().toString().toCharArray();
        for (char c : transportTypes) {
            if (c == '1') {
                labelNames.add("自提");
            }
            if (c == '2') {
                labelNames.add("线下面交");
            }
            if (c == '3') {
                labelNames.add("邮寄");
                if (itemBase.getPostage() == null || itemBase.getPostage().longValue() == 0) {
                    labelNames.add("包邮");
                }
            }
        }
        List<LabelOutput> labelOutputs = labelAtomService.selectLabelByNames(labelNames).getData();
        for (LabelOutput labelOutput : labelOutputs) {
            ItemLabelInput itemLabelInput = createItemLabel(labelOutput, itemId);
            labelInputList.add(itemLabelInput);
        }
        labelAtomService.insertLabelList(labelInputList);
        //初始化商品标签信息 end

        //初始化商品扩展信息 start
        ItemExtInput itemExtInput = new ItemExtInput();
        itemExtInput.setItemId(itemId);
        itemExtInput.setBrowser(0);
        itemExtInput.setCollection(0);
        itemExtInput.setCreateTime(now);
        itemExtInput.setDataStatus(DataStatus.USE.value());
        itemExtInput.setComment(0);
        itemExtInput.setHotcode(0);
        itemExtApiService.insertItemExt(itemExtInput);

        UserPayInput userPayInput = new UserPayInput();
        userPayInput.setId(userPayOutput.getId());
        userPayInput.setIntegral(userPayOutput.getIntegral() - itemBase.getSellingPrice().intValue());
        userPayInput.setModifyTime(now);
        iUserAtomFeignClientSvc.modUserPay(userPayInput);
        UserPayLogInput userPayLogInput = UserPayLogInput.newUserPayLog(itemBase.getUserId(), itemBase.getSellingPrice().intValue(), userPayOutput.getIntegral(), 2, "发布商品扣减积分");
        iUserAtomFeignClientSvc.addUserPayLog(userPayLogInput);
        return serviceBean;
    }

    private ItemLabelInput createItemLabel(LabelOutput labelOutput, Integer itemId) {
        ItemLabelInput itemLabelInput = new ItemLabelInput();
        itemLabelInput.setItemId(itemId);
        itemLabelInput.setLabelId(labelOutput.getId());
        itemLabelInput.setCreateTime(DateUtil.newNowDate());
        itemLabelInput.setStatus(0);
        itemLabelInput.setDataStatus(DataStatus.USE.value());
        return itemLabelInput;
    }

    @Override
    public ServiceBean<Integer> addItemDetails(InputBean<ItemDetailsInput> inputBean) {
        ItemDetailsInput itemDetails = inputBean.getParam();
        Date now = DateUtil.newNowDate();
        itemDetails.setCreateTime(now);
        itemDetails.setStatus(ItemStatus.STATUS_WAIT.value());
        itemDetails.setDataStatus(DataStatus.USE.value());
        return itemApiService.addItemDetails(itemDetails);
    }

    @Override
    public ServiceBean<String> deleteItemByItemId(InputBean<Integer> inputBean) {
        Integer itemId = inputBean.getParam();
        ItemBaseInput itemBaseInput = new ItemBaseInput();
        itemBaseInput.setItemId(itemId);
        ItemBaseOutput itemBaseOutput = itemApiService.selectItemBase(itemBaseInput).getData();
        if (itemBaseOutput.getStatus() != ItemStatus.STATUS_WAIT.value()) {
            return resultFailed("只能删除待上架商品");
        }
        if (itemBaseOutput.getUserId().intValue() != inputBean.getUserId().intValue()) {
            return resultFailed("不能删除其他用户商品");
        }
        itemBaseInput.setDataStatus(DataStatus.DELETE.value());
        ServiceBean serviceBean = itemApiService.updateItemBase(itemBaseInput);
        if (!serviceBean.isSuccess()) {
            return serviceBean;
        }
        ItemDetailsInput itemDetailsInput = new ItemDetailsInput();
        itemDetailsInput.setItemId(itemId);
        itemDetailsInput.setDataStatus(DataStatus.DELETE.value());

        //退回用户积分 begin
        UserPayOutput userPayOutput = iUserAtomFeignClientSvc.qryUserPayByUserId(inputBean.getUserId());
        UserPayInput userPayInput = new UserPayInput();
        userPayInput.setId(userPayOutput.getId());
        userPayInput.setIntegral(userPayOutput.getIntegral() + itemBaseOutput.getDiscountPrice().intValue());
        userPayInput.setModifyTime(DateUtil.newNowDate());
        iUserAtomFeignClientSvc.modUserPay(userPayInput);
        UserPayLogInput userPayLogInput = UserPayLogInput.newUserPayLog(userPayOutput.getUserId(), itemBaseOutput.getDiscountPrice().intValue(), userPayOutput.getIntegral(), 1, "删除商品，退还积分");
        iUserAtomFeignClientSvc.addUserPayLog(userPayLogInput);
        //退回用户积分 end

        ItemExtInput itemExtInput = new ItemExtInput();
        itemExtInput.setItemId(itemId);
        itemExtInput.setDataStatus(DataStatus.DELETE.value());
        return itemApiService.updateItemDetails(itemDetailsInput);
    }

    @Override
    public ServiceBean<String> deleteItemBySelective(InputBean<ItemBaseInput> inputBean) {
        ItemBaseInput itemBaseInput = inputBean.getParam();
        ServiceBean<List<ItemBaseOutput>> serviceBean = itemApiService.selectItemBaseList(inputBean);
        if (!serviceBean.isSuccess()) {
            return resultFailed();
        }
        List<ItemBaseOutput> list = serviceBean.getData();
        List<Integer> ids = new ArrayList<>();
        for (ItemBaseOutput baseOutput : list) {
            ids.add(baseOutput.getItemId());
        }
        ServiceBean serviceBean1 = itemApiService.deleteItemBaseByIds(ids);
        if (serviceBean1.isSuccess()) {
            return itemApiService.deleteItemDetailsByIds(ids);
        }
        return serviceBean1;
    }

    @Override
    public ServiceBean<?> selectItemDetails(InputBean<?> inputBean) {
        return null;
    }

    @Override
    public ServiceBean<Item> selectItem(InputBean<ItemBaseInput> inputBean) {
        ServiceBean<List<Item>> listServiceBean = itemApiService.selectItemList(inputBean);
        if (!listServiceBean.isSuccess()) {
            return resultFailed();
        }
        Item item = listServiceBean.getData().get(0);
        if (item == null) {
            return resultFailed("查询商品失败");
        }
        return resultData(item);
    }

    @Override
    public ServiceBean<ItemBaseOutput> browserItem(InputBean<ItemBaseInput> inputBean) {
        ItemBaseInput itemBaseInput = inputBean.getParam();
        //查询商品基本信息
        ServiceBean<ItemBaseOutput> baseServiceBean = itemApiService.selectItemBase(itemBaseInput);
        if (!baseServiceBean.isSuccess()) {
            return resultFailed("商品不存在或已下架");
        }
        ItemBaseOutput itemBaseOutput = baseServiceBean.getData();

        //查询商品详情
        ItemDetailsInput itemDetailsInput = new ItemDetailsInput();
        itemDetailsInput.setItemId(itemBaseInput.getItemId());
        ServiceBean<ItemDetailsOutput> detailsServiceBean = itemApiService.selectItemDetails(itemDetailsInput);
        ItemDetailsOutput itemDetailsOutput = detailsServiceBean.getData();

        //查询商品扩展信息
        ItemExtInput itemExtInput = new ItemExtInput();
        itemExtInput.setItemId(itemBaseInput.getItemId());
        ItemExtOutput itemExtOutput = itemExtApiService.selectItemExt(itemExtInput).getData();

        //更新商品浏览次数和热度
        itemExtInput.setId(itemExtOutput.getId());
        itemExtInput.setBrowser(itemExtOutput.getBrowser() + 1);
        itemExtInput.setHotcode(itemExtOutput.getHotcode() + 1);
        itemExtApiService.updateItemExt(itemExtInput);
        itemExtOutput = itemExtApiService.selectItemExt(itemExtInput).getData();

        //查询分类信息
        Category category = new Category();
        category.setCtgId(itemBaseOutput.getCategory());
        category = itemExtApiService.getCategory(category).getData();
        itemBaseOutput.setCategoryObj(category);

        //查询标签列表
        LabelInput labelInput = new LabelInput();
        labelInput.setItemId(itemBaseOutput.getItemId());
        List<LabelOutput> labelList = labelAtomService.getLabelList(labelInput).getData();

        //记录浏览足迹
        if (inputBean.getUserId() != null) {
            Integer userId = inputBean.getUserId();
            ItemFootInput itemFootInput = new ItemFootInput();
            itemFootInput.setItemId(itemBaseOutput.getItemId());
            itemFootInput.setUserId(userId);
            itemFootInput.setCreateTime(DateUtil.newNowDate());
            itemFootInput.setDataStatus(DataStatus.USE.value());
            itemExtApiService.insertItemFoot(itemFootInput);
        }

        itemBaseOutput.setLabelList(labelList);
        itemBaseOutput.setItemExt(itemExtOutput);
        itemBaseOutput.setItemDetails(itemDetailsOutput);
        return resultData(itemBaseOutput);
    }

    @Override
    public ServiceBean<List<Item>> selectItemList(InputBean<ItemBaseInput> inputBean) {
        ServiceBean<List<Item>> listServiceBean = itemApiService.selectItemList(inputBean);
        if (!listServiceBean.isSuccess()) {
            return resultFailed();
        }
        List<Item> itemList = listServiceBean.getData();
        if (itemList == null || itemList.isEmpty()) {
            return resultFailed("查询商品列表失败");
        }
        return resultData(itemList);
    }

    @Override
    public ServiceBean<Map<String, Object>> selectItemList4P(InputBean<ItemBaseInput> inputBean) {
        ServiceBean<Map<String, Object>> listServiceBean = itemApiService.selectItemList4P(inputBean);
        if (!listServiceBean.isSuccess()) {
            return resultFailed();
        }
        return listServiceBean;
    }

    @Override
    public ServiceBean<String> mdfItemStatus(InputBean<ItemBaseInput> inputBean) {
        ItemBaseInput itemBaseInput = inputBean.getParam();
        return itemApiService.mdfItemStatus(itemBaseInput);
    }


}
